/**
 * @name axios
 * @desc 请求方法定义文件
 */
//Axios是一个基于Promise（ES6中用于处理异步的）的HTTP库，用于浏览器和node.js中，API
import axios from "axios"

//process 对象是一个 global （全局变量）
//process.env属性返回项目运行所在环境的一些信息,判断是开发（development）还是生产模式（production）
const isDevelopment = process.env.NODE_ENV === "development"

const httpRegx = /^http(s*):\/\//
const customProxyRegx = /^\/api[a-zA-Z-_]*/
const defaultProxy = "/proxy"

function withProxy(url = "") {
  if (httpRegx.test(url)) {
    return url
  }
  if (customProxyRegx.test(url)) {
    return isDevelopment ? url : url.replace(customProxyRegx, "")
  } else {
    return isDevelopment ? defaultProxy + url : url
  }
}

const axiosIns = axios.create({
  timeout: 10000,
  responseType: "json",
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  }
})

axiosIns.interceptors.request.use(
  config => {
    // const token = window.localStorage.getItem('token')
    const token = "c5f1c4480768441b9bb47762f33f3c5b"
    !!token && (config.headers["Authorization"] = token)
    config.url = withProxy(config.url)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

axiosIns.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

export const get = (url = "", params = null, config = {}) => axiosIns.get(url, { ...config, params })

export const post = axiosIns.post
export const all = axiosIns.all
